package com.goldplusgold.tradedelay.app.my.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.goldplusgold.imageloader.lib.GlideCircleTransform;
import com.goldplusgold.live.LVDataManager;
import com.goldplusgold.live.bean.SwitchBean;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.example.account.manager.AppCacheSharedPreferences;
import com.goldplusgold.support.lib.utils.Logger;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.ReplaceStrByAsteriskUtil;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.tradedelay.app.base.widget.MyAlertDialog;
import com.goldplusgold.tradedelay.app.home.pojo.TDLogin;
import com.goldplusgold.tradedelay.app.home.serivce.HomeService;
import com.goldplusgold.tradedelay.app.main.activity.TDMainActivity;
import com.example.account.manager.ParmasKey;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.tradedelay.app.my.activity.MyFollowActivity;
import com.goldplusgold.tradedelay.app.my.activity.QuestionsActivity;
import com.goldplusgold.tradedelay.app.my.activity.UserActivity;
import com.goldplusgold.tradedelay.app.my.networkservice.ApiConfig;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.Switch;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MyFragment extends BaseFragment implements Handler.Callback {

    @BindView(R.id.iv_head_image)
    ImageView ivHeadImage;
    //交易客户号
    @BindView(R.id.tv_trade_num)
    TextView tvTradeNum;
    @BindView(R.id.id_trade_no_layout)
    LinearLayout mTradeNoLayout;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.txt_login)
    TextView txtLogin;
    @BindView(R.id.iv_right_arrow)
    ImageView ivRightArrow;
    @BindView(R.id.rl_trade_num)
    RelativeLayout mTradeNum;

    @BindView( R.id.rl_question_us)
    RelativeLayout mQuestionLayout ;

    public static final int REQUEST_PERSON_INFORMATION_CODE = 0x02;
    public static final int REQUEST_SETTING_CODE = 0x03;
    public static final int MY_PERMISSION_REQUEST_CALL_PHONE = 20;
    private UserInfo mUserInfo;
    private boolean mWechatState = false;//微信登录状态
    private Handler handler = new Handler(this);

    public static MyFragment newInstance() {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {
        super.initView();
        if (MyService.getInstance().isLogin()) {
            txtLogin.setVisibility(View.GONE);
            tvUserName.setVisibility(View.VISIBLE);
        } else {
            Glide.with(getActivity()).load(R.drawable.head_image_unlogin).into(ivHeadImage);
        }
        requestSwitch();
    }

    private void requestSwitch(){
        //判断其是否显示
        LVDataManager.getInstance().getSwitch(new Callback<SwitchBean>() {
            @Override
            public void onResponse(Call<SwitchBean> call, Response<SwitchBean> response) {
                SwitchBean bean = response.body();
                if(bean != null) {
                    if (bean.isColumnFlag() == false && bean.isVideoFlag() == false) {
                        mQuestionLayout.setVisibility(View.GONE);
                    } else {
                        mQuestionLayout.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onFailure(Call<SwitchBean> call, Throwable t) {
                Logger.e("requestSwitch",t.toString());
            }
        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (MyService.getInstance().isLogin()) {
                new LoadUserInfoAsyncTask().execute(AsyncTask.TYPE_NET);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        showHasLoginPage();
        if (MyService.getInstance().isLogin()) {
            new LoadUserInfoAsyncTask().execute(AsyncTask.TYPE_NET);
            new QueryTdLoginStateTask().execute(AsyncTask.TYPE_NET);
        }
    }

    @OnClick({R.id.rl_my_info, R.id.rl_trade_num, R.id.rl_novice_classroom, R.id.rl_customer_service, R.id.rl_setting, R.id.rl_follow_us , R.id.rl_question_us})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_my_info:
                if (MyService.getInstance().isLogin()) {
                    String headImage = "";
                    String userName = "";
                    String wechatName = "";
                    if (mUserInfo != null) {
                        headImage = mUserInfo.getHeadImage();
                        userName = mUserInfo.getUserName();
                        wechatName = mUserInfo.getWechatName();
                        mWechatState = mUserInfo.getWechatState();
                    }
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    intent.putExtra("fromPage", "PersonalInfo");
                    intent.putExtra("headImage", headImage);
                    intent.putExtra("userName", userName);
                    intent.putExtra("wechatName", wechatName);
                    intent.putExtra("wechatState", mWechatState);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivityForResult(intent, REQUEST_PERSON_INFORMATION_CODE);
                }
                break;
            case R.id.rl_trade_num:
                new QuerySwitchStateTask().execute(AsyncTask.TYPE_NET);
                break;
            case R.id.rl_novice_classroom:
                ActivityUtils.gotoActionBrowserPage(getActivity(), ApiConfig._NOVICE_CLASSROOM_URL);
                break;
            case R.id.rl_customer_service:
                showDialRemindDialog();
                break;
            case R.id.rl_setting:
                if (MyService.getInstance().isLogin()) {
                    ActivityUtils.gotoUserWebview(getActivity(), ApiConfig._MY_SETTING_URL);
                } else {
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivityForResult(intent, REQUEST_SETTING_CODE);
                }
                break;
            /*case R.id.rl_about_us:
                ActivityUtils.gotoActionBrowserPage(getActivity(), ApiConfig._ABOUT_US_URL);
                break;*/
            case R.id.rl_follow_us:
                if (MyService.getInstance().isLogin()) {
                    startActivity(new Intent(getActivity() , MyFollowActivity.class));
                } else {
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivityForResult(intent, REQUEST_SETTING_CODE);
                }
                break;
            case R.id.rl_question_us:
                if(AppCacheSharedPreferences.getCacheBoolean(ParmasKey.login_state , false)){
                    startActivity(new Intent(getActivity() , QuestionsActivity.class));
                }else{
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivityForResult(intent, REQUEST_SETTING_CODE);
                }
                break;
        }
    }

    void showDialRemindDialog() {
        new MyAlertDialog(getActivity()).builder().setTitle("温馨提示")
                .setMsg("确定拨打电话:" + "0571-56663666")
                .setPositiveButton(getActivity().getString(R.string.action_positive), new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        //check if permissions are granted
                        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                            requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSION_REQUEST_CALL_PHONE);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "0571-56663666"));

                            startActivity(intent);
                        }


                    }
                }).setNegativeButton(getActivity().getString(R.string.action_negative), new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == MY_PERMISSION_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "0571-56663666"));
                startActivity(intent);
            } else {
                // Permission Denied
                Toast.makeText(getContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void showHasLoginPage() {
        if (MyService.getInstance().isLogin()) {
            txtLogin.setVisibility(View.GONE);
            tvUserName.setVisibility(View.VISIBLE);
            ivRightArrow.setVisibility(View.VISIBLE);
        } else {
            txtLogin.setVisibility(View.VISIBLE);
            tvUserName.setVisibility(View.GONE);
            ivRightArrow.setVisibility(View.GONE);
            Glide.with(getActivity()).load(R.drawable.head_image_unlogin).into(ivHeadImage);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE:
                String message = (String) msg.obj;
                if (getActivity() != null && getActivity() instanceof TDMainActivity) {
                    if (((TDMainActivity) getActivity()).mMainViewPager.getCurrentItem() == 3) {
                        ActivityUtils.forceQuit(getActivity(), message);
                    }
                }
                break;
        }

        return true;
    }

    public class LoadUserInfoAsyncTask extends AsyncTask<Void, Void, UserInfo> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {

            try {
                UserInfo userInfo = MyService.getInstance().getUserInfo();
                if (userInfo != null) {
                    return userInfo;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);

            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (userInfo == null) {
                return;
            }

            mUserInfo = userInfo;

            AppCacheSharedPreferences.putCacheBoolean(ParmasKey.login_state  , true);
            AppCacheSharedPreferences.putCacheString(ParmasKey.token , mUserInfo.getToken());

            Glide.with(getActivity()).load(userInfo.getHeadImage()).error(R.drawable.head_image_default).transform(new GlideCircleTransform(getActivity())).into(ivHeadImage);
            tvUserName.setText(ReplaceStrByAsteriskUtil.hideMidFourPhoneNum(userInfo.getUserName()));
        }
    }


    public class QueryTdLoginStateTask extends AsyncTask<Void, Void, TDLogin> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected TDLogin doInBackground(Void... params) {

            try {
                TDLogin tdLoginState = HomeService.getInstance().getTDLoginState();
                if (tdLoginState != null) {
                    return tdLoginState;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(TDLogin tdLogin) {
            super.onPostExecute(tdLogin);
            if (!isAvailableActivity()) {
                return;
            }
            if (tdLogin == null) {
                return;
            }

            if (tdLogin.getStatus()) {
                tvTradeNum.setVisibility(View.VISIBLE);
                tvTradeNum.setText(tdLogin.getInfo());
                mTradeNoLayout.setVisibility(View.GONE);
                mTradeNum.setEnabled(false);
            } else {
                tvTradeNum.setVisibility(View.GONE);
                mTradeNoLayout.setVisibility(View.VISIBLE);
                mTradeNum.setEnabled(true);
            }
        }
    }


    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_PERSON_INFORMATION_CODE || requestCode == REQUEST_SETTING_CODE)
                && resultCode == getActivity().RESULT_OK) {
            txtLogin.setVisibility(View.GONE);
            tvUserName.setVisibility(View.VISIBLE);
            ivRightArrow.setVisibility(View.VISIBLE);
            new LoadUserInfoAsyncTask().execute(AsyncTask.TYPE_NET);
        }
    }

    public class QuerySwitchStateTask extends AsyncTask<Void, Void, Switch> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Switch doInBackground(Void... params) {
            Switch switchValue = null;
            try {
                switchValue = TradeService.getInstance().getSwitch();
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return switchValue;
        }

        @Override
        protected void onPostExecute(Switch switchValue) {
            super.onPostExecute(switchValue);
            if (switchValue == null) {
                return;
            }
            if (!switchValue.isSwitchFlag()) {
                Activity activity = getActivity();
                if (activity instanceof TDMainActivity) {
                    ((TDMainActivity) activity).mTabTrade.setChecked(true);
                    ((TDMainActivity) activity).mMainViewPager.setCurrentItem(2, false);
                }
            } else {
                ActivityUtils.gotoTradeLogin(getActivity());
            }
        }
    }

}